﻿using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.Linq;
using System.Linq;
using Interactive.Utility.Linq;

namespace Interactive.Utility.Extension {
    /// <summary>
    /// 参考http://jeffreyzhao.cnblogs.com/archive/2008/02/19/using-translate-method-and-modify-command-text-before-query-in-linq-to-sql.html
    /// 为了解决只用获取大对象中的一小部分问题
    /// 在呼啦圈项目中有应用,比如获取帖子列表,没有必要获取帖子内容
    /// </summary>
    public static class DataContextExt {
        public static List<T> GetCosttomList<T>(this DataContext dataContext, IQueryable query){
            DbCommand command = dataContext.GetCommand(query);
            dataContext.OpenConnection();

            using (DbDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
                return dataContext.Translate<T>(reader).ToList();
        }

        private static void OpenConnection(this DataContext dataContext){
            if (dataContext.Connection.State == ConnectionState.Closed)
                dataContext.Connection.Open();
        }


        public static List<T> GetCosttomList<T,V>(this DataContext<V> dataContext, IQueryable query) where V :class 
        {
            DbCommand command = dataContext.GetCommand(query);
            dataContext.OpenConnection();

            using (DbDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
                return dataContext.Translate<T>(reader).ToList();
        }

       
    }
}